package com.ntu.rent.common.typeadapter;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class SqlDateTypeAdapter implements JsonSerializer<java.sql.Date>, JsonDeserializer<java.sql.Date>{
    private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
    public JsonElement serialize(java.sql.Date ts, Type t, JsonSerializationContext jsc) {    
        String dfString = format.format(new Date(ts.getTime()));    
        return new JsonPrimitive(dfString);    
    }    
    public java.sql.Date deserialize(JsonElement json, Type t, JsonDeserializationContext jsc) throws JsonParseException {    
        if (!(json instanceof JsonPrimitive)) {    
            throw new JsonParseException("The date should be a string value");    
        }    
   
        try {    
            Date date = format.parse(json.getAsString());    
            return new java.sql.Date(date.getTime());    
        } catch (Exception e) {    
            throw new JsonParseException(e);    
        }    
    }    
} 
